﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Test_2D
{
    public partial class PlayForm : Form
    {
        public PlayForm(Canvas _canvas, Animation _animation)
        {
            InitializeComponent();
            this.ClientSize = _canvas.Size;
            this.BackColor = _canvas.Color;
            canvas = _canvas;
            animation = _animation; 
            play();
        }

        private Canvas canvas;
        private Animation animation;
        private int speed = 100;

        private int cur_frame;
        private Graphics g;

        
        private void play()
        {
            cur_frame = 0;
            g = this.CreateGraphics();
            timer1.Interval = speed;

            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            g.Clear(this.BackColor);
            int timelineMiss = 0;   //在指定帧号下，没有此帧的时间轴的个数
            for (int i = 0; i < animation.TimeLines.Count; i++)
            {
                if (cur_frame > animation.TimeLines[i].Frames.Count - 2)    //预测，下一个帧号是否超出时间轴的长度
                    timelineMiss++;

                if (cur_frame > animation.TimeLines[i].Frames.Count - 1 ||
                    animation.TimeLines[i].Frames[cur_frame] == null)
                    //如果帧号超出了时间轴的长度或帧为null，则不绘制此帧
                    continue;

                for (int j = 0; j < animation.TimeLines[i].Frames[cur_frame].Motions.Count; j++)
                {
                    Motion tmp_mot = animation.TimeLines[i].Frames[cur_frame].Motions[j];
                    g.DrawImage(tmp_mot.Image, new Point(tmp_mot.Location.X + canvas.Offset.X, tmp_mot.Location.Y + canvas.Offset.Y));
                }
            }

            if (timelineMiss >= animation.TimeLines.Count)      //所有时间轴都没有下一个帧
            {
                cur_frame = 0;      //重新开始
            }
            else
            {
                cur_frame++;
            }
        }

        private void 暂停ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            timer1.Stop();
        }

        private void 继续ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            timer1.Start();
        }

        private void 从新开始ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            play();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }  
}
